import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class CustomToast {
  // toast靠它加到屏幕上
  static OverlayEntry? _overlayEntry;

  // toast是否正在showing
  static bool _showing = false;

  // 开启一个新toast的当前时间，用于对比是否已经展示了足够时间
  static late DateTime _startedTime;

  // 提示内容
  static late String _msg;

  // toast显示时间
  static late int _showTime;

  // 背景颜色
  static late Color _bgColor;

  // 文本颜色
  static late Color _textColor;

  // 文字大小
  static late double _textSize;

  // 左右边距
  static late double _pdHorizontal;

  // 上下边距
  static late double _pdVertical;

  // 图片
  static  late IconData _iconData;

  // 图片颜色
  static late Color _iconColor;

  static void success(
      BuildContext context, {
        //显示的文本
        required String msg,
        //显示的时间 单位毫秒
        int showTime = 1000,
        //显示的背景
        Color bgColor = Colors.white,
        //显示的文本颜色
        Color textColor = Colors.black,
        //显示的文字大小
        double textSize = 16.0,
        //文字水平方向的内边距
        double pdHorizontal = 20.0,
        //文字垂直方向的内边距
        double pdVertical = 10.0,

        IconData iconData = Icons.check,

        Color iconColor  = Colors.green,
      }) async {
    assert(msg != null);
    _msg = msg;
    _startedTime = DateTime.now();
    _showTime = showTime;
    _bgColor = bgColor;
    _textColor = textColor;
    _textSize = textSize;
    _pdHorizontal = pdHorizontal;
    _pdVertical = pdVertical;
    _iconColor = iconColor;
    _iconData = iconData;
    //获取OverlayState
    OverlayState overlayState = Overlay.of(context);
    _showing = true;
    if (_overlayEntry == null) {
      //OverlayEntry负责构建布局
      //通过OverlayEntry将构建的布局插入到整个布局的最上层
      _overlayEntry = OverlayEntry(
          builder: (BuildContext context) => Container(
              alignment: Alignment.center,
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              color: Colors.black26,
              child: AnimatedOpacity(
                opacity: _showing ? 1.0 : 0.0, //目标透明度
                duration: _showing
                    ? Duration(milliseconds: 100)
                    : Duration(milliseconds: 400),
                child: _buildSuccessToastWidget(),
              )));
      //插入到整个布局的最上层
      overlayState.insert(_overlayEntry!);
    } else {
      //重新绘制UI，类似setState
      _overlayEntry?.markNeedsBuild();
    }
    // 等待时间
    await Future.delayed(Duration(milliseconds: _showTime));
    //2秒后 到底消失不消失
    if (DateTime.now().difference(_startedTime).inMilliseconds >= _showTime) {
      _showing = false;
      _overlayEntry?.markNeedsBuild();
      await Future.delayed(Duration(milliseconds: 400));
      _overlayEntry?.remove();
      _overlayEntry = null;
    }
  }

  //toast绘制
  static _buildSuccessToastWidget() {
    return Card(
      color: _bgColor,
      margin: EdgeInsets.only(left: 30, right: 30),
      child: Padding(
          padding: EdgeInsets.symmetric(
              horizontal: _pdHorizontal, vertical: _pdVertical),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(_iconData, size: 60, color: _iconColor,),
              Text(
                _msg,
                style: TextStyle(
                  fontSize: _textSize,
                  color: _textColor,
                ),
              ),
              SizedBox(height: 15,),
            ],
          )
      ),
    );
  }
  static   Future<void> showTipToast(
      BuildContext context,
      String message, {
        Duration duration = const Duration(seconds: 1),
        double marginFromTop = 100,
      }) async {
    final overlayState = Overlay.of(context);
    if (overlayState == null) return;

    // 使用一个 ValueNotifier 控制透明度（用于淡入淡出动画）
    final opacity = ValueNotifier<double>(0.0);

    final overlayEntry = OverlayEntry(
      builder: (context) {
        return Positioned(
          top: marginFromTop,
          left: 20,
          right: 20,
          child: IgnorePointer(
            // 关键：忽略事件，让下面页面继续接收手势
            ignoring: true,
            child: Material(
              color: Colors.transparent,
              child: SafeArea(
                top: false,
                bottom: false,
                child: ValueListenableBuilder<double>(
                  valueListenable: opacity,
                  builder: (context, value, child) {
                    return Opacity(
                      opacity: value,
                      child: child,
                    );
                  },
                  child: Center(
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 14, vertical: 8),
                      decoration: BoxDecoration(
                        color: Colors.black87,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Text(
                        message,
                        style: const TextStyle(color: Colors.white, fontSize: 14),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );

    // 插入到 overlay
    overlayState.insert(overlayEntry);

    // 动画：淡入 -> 保持 -> 淡出
    try {
      // 淡入
      opacity.value = 0.0;
      await Future.delayed(const Duration(milliseconds: 10));
      opacity.value = 1.0;

      // 保持显示 duration（例如 1 秒）
      await Future.delayed(duration);

      // 淡出
      opacity.value = 0.0;
      // 给淡出一点时间（可调整）
      await Future.delayed(const Duration(milliseconds: 200));
    } finally {
      overlayEntry.remove();
      opacity.dispose();
    }
  }

}
